<template>
  <div class="departments-container">
    <el-card class="box-card">
      <template>
        <!-- 表头导航 -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="组织结构" name="first" style="padding:0 80px">
            <!-- 弹性布局盒子 -->
            <el-row type="flex" justify="space-between">
              <el-col :span="5">深圳传智播客教育科技股份有限公司</el-col>
              <el-col :span="5" style="text-align:right;margin-right:10px">
                负责人
                <!-- 下拉菜单 -->
                <el-dropdown trigger="click" style="margin-left:20px">
                  <span class="el-dropdown-link">
                    操作
                    <i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-button type="text" @click="addDepartment('')">
                      添加部门
                    </el-button>
                  </el-dropdown-menu>
                </el-dropdown></el-col>
            </el-row>
            <!-- 分割线 -->
            <div class="halving">
              <el-divider />
            </div>
            <!-- 树形控件,菜单栏 -->
            <el-tree v-loading="loading" :data="departs">
              <el-row
                slot-scope="{ data }"
                type="flex"
                justify="space-between"
                style="width:100%"
              >
                <el-col :span="5">{{ data.name }}</el-col>
                <el-col :span="5" style="text-align:right;margin-right:10px">
                  {{ data.manager }}
                  <!-- 下拉菜单 -->
                  <el-dropdown trigger="click" style="margin-left:20px">
                    <span class="el-dropdown-link">
                      操作
                      <i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-button type="text" @click="addDepartment(data.id)">
                        添加子部门
                      </el-button>
                      <el-button type="text" @click="checkDepartment(data.id)">
                        查看部门
                      </el-button>
                      <el-button type="text" @click="delDepartment(data.id)">
                        删除部门
                      </el-button>
                    </el-dropdown-menu>
                  </el-dropdown></el-col>
              </el-row>
            </el-tree>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="depForm" :model="form" :rules="rules">
        <el-form-item
          label="部门名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门编码"
          :label-width="formLabelWidth"
          prop="code"
        >
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门负责人"
          :label-width="formLabelWidth"
          prop="manager"
        >
          <el-select
            v-model="form.manager"
            style="tetx-algin:left"
            @focus="employeesList"
          >
            <el-option
              v-for="item in staffList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门介绍"
          :label-width="formLabelWidth"
          prop="introduce"
        >
          <el-input v-model="form.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="verifyForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  // 获取全部部门接口
  getDepartmentList,
  // 添加部门接口
  addDepartmentDetails,
  // 获取部门信息接口
  getDepartmentDetails,
  // 修改部门详情
  alterDepartmentDetails,
  // 删除部门
  delDepartmentDetails
} from '@/api/Structure'
// 获取部门负责人接口
import { getEmployeesList } from '@/api/employees'
//
import { formatData } from '@/utils/index'
export default {
  name: 'Departments',
  data() {
    // 部门名称自定义表单验证
    const MyValidate = async(rule, value, callback) => {
      const res = await getDepartmentList()
      res.depts.filter(v => {
        if (v.name === value) {
          return true
        } else {
          return false
        }
      }).length === 0
        ? callback()
        : callback(new Error('有重复名称，请重新输入'))
    }
    // 部门编码自定义表单验证
    const MyValidateCode = async(rule, value, callback) => {
      const res = await getDepartmentList()
      res.depts.filter(v => {
        if (v.code === value) {
          return true
        } else {
          return false
        }
      }).length === 0
        ? callback()
        : callback(new Error('有重复编码，请重新输入'))
    }
    return {
      // 数据加载是否显示loading
      loading: false,
      activeName: 'first',
      // 部门数据
      departs: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 是否显示弹窗
      dialogFormVisible: false,
      // 弹窗信息
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      // 左侧名称宽度
      formLabelWidth: '120px',
      // 管理员数据
      staffList: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '名称长度在3到10个字符',
            trigger: 'blur'
          },
          { validator: MyValidate, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '编码长度在3到10个字符',
            trigger: 'blur'
          },
          { validator: MyValidateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '负责人名称不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 100,
            message: '介绍长度在3到100个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑部门' : '添加部门'
    }
  },
  created() {
    // 调用方法，打开页面获取全部部门信息
    this.getDetails()
  },
  methods: {
    // 获取全部部门信息
    async getDetails() {
      // 打开loading动画
      this.loading = true
      const res = await getDepartmentList()
      // 递归基于给定的pid返回满足条件的数组

      // 调用方法遍历二三维数组等
      const data = formatData(res.depts, '')
      this.departs = data
      // 关闭loading动画
      setTimeout(() => {
        this.loading = false
      }, 1000)
    },
    // 编辑部门信息
    async checkDepartment(id) {
      this.dialogFormVisible = true
      const res = await getDepartmentDetails({ id: id })
      this.form = res
      this.form.id = id
    },
    // 添加子部门
    async addDepartment(pid) {
      this.form = {}
      this.dialogFormVisible = true
      this.form.pid = pid
    },
    // 获取管理员信息
    async employeesList() {
      const res = await getEmployeesList()
      this.staffList = res
    },
    // 删除部门
    async delDepartment(id) {
      const res = await delDepartmentDetails({ id: id })
      this.$message.success('删除部门成功')
      this.getDetails()
    },
    // 校验表单
    verifyForm() {
      this.$refs.depForm.validate(async v => {
        if (v) {
          if (this.form.id) {
            const res = await alterDepartmentDetails(this.form)
            this.$message.success('编辑部门成功')
          } else {
            const res = await addDepartmentDetails(this.form)
            this.$message.success('新增部门成功')
          }
          this.getDetails()
          this.dialogFormVisible = false
          this.form = {
            name: '',
            code: '',
            manager: '',
            introduce: '',
            pid: ''
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.departments-container {
  padding: 15px;
  .box-card {
    width: 100%;
  }
  .el-row {
    font-size: 14px;
  }

  .el-divider {
    margin: 10px 0 0;
  }
  .el-dialog__header {
    background-color: #66b1ff;
    .el-dialog__title,
    .el-dialog__close {
      color: white;
    }
  }
}
.el-dropdown-menu {
  padding: 0 20px;
  .el-button {
    display: block;
  }
}

div.el-tabs__content {
  padding: 0 80px;
}
</style>
